const fs = require('fs');
const path = require('path')
const pluginName = 'ResourceImport';
function copy(from, to) {
  const fromPath = path.resolve(from)
  const toPath = path.resolve(to)
  fs.access(toPath, function (err) {
    if (err) {
      fs.mkdirSync(toPath)
    }
  })
  fs.readdir(fromPath, function (err, paths) {
    if (err) {
      console.log(err)
      return
    }
    paths.forEach(function (item) {
      const newFromPath = fromPath + '/' + item
      const newToPath = path.resolve(toPath + '/' + item)

      fs.stat(newFromPath, function (err, stat) {
        if (err) return
        if (stat.isFile() && !fs.existsSync(newToPath)) {
          copyFile(newFromPath, newToPath)
        }
        if (stat.isDirectory()) {
          copy(newFromPath, newToPath)
        }
      })
    })
  })
}

function copyFile(from, to) {
  fs.copyFileSync(from, to, function (err) {
    if (err) {
      console.log(err)
      return
    }
  })
}

class ResourceImportPlugin {
  constructor(options = {
    moduleName: '',
    importList:[
      {
        fromDirectory: '',
        toDirectory: '',
      }
    ],

    callback: () => {},}) {
    this.options = options;
    this.modules = {};
    this.importResourceFiles();
  }

  importResourceFiles() {
    if (this.options.moduleName && this.options.importList && this.options.importList.length>0) {
      this.options.importList.forEach(option=>{
        if(option.fromDirectory && option.toDirectory){
          const fromFilePath = path.resolve(process.cwd(), 'node_modules', this.options.moduleName,option.fromDirectory);
          const sourceFilePath = path.resolve(process.cwd(),option.toDirectory);
          copy(fromFilePath, sourceFilePath);//复制资源
        }
      })
    }
  }

  handleFinishModules(module) {
  }

  handleBuildModule(module) {
  }

  handleSucceedModule(module) {
  }

  apply(compiler) {
    compiler.hooks.compilation.tap(
        pluginName, compilation => {
          compilation.hooks.buildModule.tap(
              pluginName,
              this.handleBuildModule.bind(this)
          );

          compilation.hooks.succeedModule.tap(
              pluginName,
              this.handleSucceedModule.bind(this));

          compilation.hooks.finishModules.tap(
              pluginName,
              this.handleFinishModules.bind(this)
          );
        }
    );
  }
}

module.exports = ResourceImportPlugin;
